package com.matrix.yukun.matrix.main_module.wallpaper.activity;

import android.app.WallpaperManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.matrix.yukun.matrix.AppConstant;
import com.matrix.yukun.matrix.BaseActivity;
import com.matrix.yukun.matrix.R;
import com.matrix.yukun.matrix.main_module.dialog.ShareDialog;
import com.matrix.yukun.matrix.main_module.entity.CollectsInfo;
import com.matrix.yukun.matrix.main_module.entity.CommentInfo;
import com.matrix.yukun.matrix.main_module.entity.PhoneCategoryInfo;
import com.matrix.yukun.matrix.main_module.entity.WallpaperInfo;
import com.matrix.yukun.matrix.main_module.index.activiy.ImageDetailActivity;
import com.matrix.yukun.matrix.main_module.index.activiy.MainActivity;
import com.matrix.yukun.matrix.main_module.netutils.NetworkUtils;
import com.matrix.yukun.matrix.main_module.utils.DownLoadUtils;
import com.matrix.yukun.matrix.main_module.utils.FileUtils;
import com.matrix.yukun.matrix.main_module.utils.SPUtils;
import com.matrix.yukun.matrix.main_module.utils.ScreenUtil;
import com.matrix.yukun.matrix.main_module.utils.ToastUtils;
import com.matrix.yukun.matrix.main_module.wallpaper.adapter.RVCommentAdapter;
import com.matrix.yukun.matrix.tool_module.gif.dialog.LoadDialog;
import com.matrix.yukun.matrix.util.DataUtils;
import com.matrix.yukun.matrix.util.FileCreateUtil;
import com.matrix.yukun.matrix.util.FileUtil;
import com.matrix.yukun.matrix.util.glide.GlideUtil;
import com.matrix.yukun.matrix.util.log.LogUtil;
import com.miracle.view.imageeditor.layer.photoview.PhotoView;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class WallpaperPreviewActivity extends BaseActivity {


    @BindView(R.id.rl_root)
    RelativeLayout rlRoot;
    @BindView(R.id.photoview)
    PhotoView photoview;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_share)
    ImageView ivShare;
    @BindView(R.id.tv_like_count)
    TextView tvLikeCount;
    @BindView(R.id.tv_collect)
    TextView tvCollect;
    @BindView(R.id.tv_comment_count)
    TextView tvCommentCount;
    @BindView(R.id.ll_collect)
    LinearLayout llCollect;
    @BindView(R.id.ll_comment)
    LinearLayout llComment;
    @BindView(R.id.ll_set_wallpaper)
    LinearLayout llSetWallpaper;
    @BindView(R.id.ll_download_image)
    LinearLayout llDownloadImage;
    @BindView(R.id.rl_mamanger)
    RelativeLayout rlMamanger;
    private WallpaperInfo mWallpaperInfo;
    private BottomSheetDialog mBottomSheetDialog;
    private BottomSheetBehavior mDialogBehavior;
    private String url = "http://service.picasso.adesk.com/v2/vertical/vertical/";
    List<CommentInfo> commentInfos = new ArrayList<>();
    private RVCommentAdapter mRvCommentAdapter;
    private boolean mIsPhone;
    private int skip;
    private RecyclerView mRecyclerView;
    private LoadDialog mLoadDialog;

    public static void start(Context context, WallpaperInfo wallpaperInfo, boolean isPhone) {
        Intent intent = new Intent(context, WallpaperPreviewActivity.class);
        intent.putExtra("data", wallpaperInfo);
        intent.putExtra("isPhone", isPhone);
        context.startActivity(intent);
    }

    @Override
    public int getLayout() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        return R.layout.activity_wallpaper_preview;
    }

    @Override
    public void initView() {
        mWallpaperInfo = (WallpaperInfo) getIntent().getSerializableExtra("data");
        mIsPhone = getIntent().getBooleanExtra("isPhone", false);
        ButterKnife.bind(this);
        if (mIsPhone) {
            photoview.setScaleType(ImageView.ScaleType.CENTER_CROP);
        }
        GlideUtil.loadImage(mWallpaperInfo.getPreview(), photoview);
        tvCollect.setText(DataUtils.transNumber(mWallpaperInfo.getFavs()));
        tvLikeCount.setText(DataUtils.transNumber(mWallpaperInfo.getRank()));
        mLoadDialog = LoadDialog.getInstance();
    }

    @Override
    public void initDate() {

        NetworkUtils.networkGet(url + mWallpaperInfo.getId() + "/comment")
                .addParams("limit", 100 + "")
                .addParams("skip", skip + "")
                .addParams("adult", "false")
                .addParams("first", 1 + "")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(response);
                            String msg = jsonObject.optString("msg");
                            if (msg.equals("success")) {
                                JSONObject res = jsonObject.optJSONObject("res");
                                Gson gson = new Gson();
                                if (res.has("comment")) {
                                    List<CommentInfo> vertical = gson.fromJson(res.optJSONArray("comment").toString(), new TypeToken<List<CommentInfo>>() {
                                    }.getType());
                                    if (vertical.size() > 0) {
                                        commentInfos.addAll(vertical);
                                    }
                                    tvCommentCount.setText(commentInfos.size() + "");
//                                if (mRvCommentAdapter != null) {
//                                    mRvCommentAdapter.setNewData(commentInfos);
//                                    mRvCommentAdapter.loadMoreComplete();
//                                }
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    @Override
    public void initListener() {
        llComment.setOnClickListener(v -> showBottomDialog());
        llCollect.setOnClickListener(v -> {
            CollectsInfo collectInfo = new CollectsInfo();
            collectInfo.setHeader(mWallpaperInfo.getThumb());
            collectInfo.setCover(mWallpaperInfo.getPreview());
            collectInfo.setTitle(mWallpaperInfo.getDesc());
            collectInfo.setName("壁纸");
            collectInfo.setType(2);
            collectInfo.setPlay_url(mWallpaperInfo.getPreview());
            collectInfo.setGif(false);
            collectInfo.save();
            showToast("收藏成功");
        });
    }

    private void showBottomDialog() {
        if (mBottomSheetDialog == null) {
            View view = View.inflate(WallpaperPreviewActivity.this, R.layout.dialog_bottomsheet, null);
            mRecyclerView = view.findViewById(R.id.recyclerview);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
            mRecyclerView.setLayoutManager(linearLayoutManager);
            mRvCommentAdapter = new RVCommentAdapter(R.layout.bottom_dialog_layout, commentInfos);
            mRecyclerView.setAdapter(mRvCommentAdapter);
            mBottomSheetDialog = new BottomSheetDialog(WallpaperPreviewActivity.this);
            mBottomSheetDialog.setContentView(view);
            BottomSheetBehavior
                    mDialogBehavior = BottomSheetBehavior.from((View) view.getParent());
            mDialogBehavior.setPeekHeight(ScreenUtil.getDisplayHeight() * 6 / 10);//dialog的高度
            mDialogBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
                @Override
                public void onStateChanged(@NonNull View view, int i) {
                    if (i == BottomSheetBehavior.STATE_HIDDEN) {
                        mBottomSheetDialog.dismiss();
                        mDialogBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                    }
                }

                @Override
                public void onSlide(@NonNull View view, float v) {

                }
            });

            mRvCommentAdapter.setOnItemChildClickListener((adapter, item, position) -> {
                if (commentInfos.get(position) != null) {
                    ImageDetailActivity.start(this, commentInfos.get(position).getUser().getAvatar(), false);
                }
            });
//            mRvCommentAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
//                @Override
//                public void onLoadMoreRequested() {
//                    skip = skip + 12;
//                    initDate();
//                }
//            }, mRecyclerView);
            mBottomSheetDialog.show();
        } else {
            mBottomSheetDialog.show();
        }
    }

    @OnClick({R.id.iv_back, R.id.iv_share, R.id.ll_comment, R.id.ll_download_image, R.id.ll_set_wallpaper})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_share:
                ShareDialog.getInstance("wallpaper", mWallpaperInfo.getPreview(), mWallpaperInfo.getPreview())
                        .show(getSupportFragmentManager(), "");
                break;
            case R.id.ll_comment:
                if (commentInfos.size() > 0) {
                    showBottomDialog();
                } else {
                    showToast("没有评论");
                }
                break;
            case R.id.ll_download_image:
                if (mLoadDialog != null) {
                    mLoadDialog.show(getSupportFragmentManager(), "");
                }
                if (mWallpaperInfo.getPreview().startsWith("http")) {
                    showToast("Download...");
                    DownLoadUtils.download(this, mWallpaperInfo.getPreview(), SPUtils.getWallpaperPath(), false);
                } else {
                    ToastUtils.showToast("无法下载");
                }
                if (mLoadDialog != null) {
                    mLoadDialog.dismiss();
                }
                break;
            case R.id.ll_set_wallpaper:
                if (mLoadDialog != null) {
                    mLoadDialog.show(getSupportFragmentManager(), "");
                }
                Glide.with(this).asBitmap().load(mWallpaperInfo.getPreview()).into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                        WallpaperManager mWallManager = WallpaperManager.getInstance(WallpaperPreviewActivity.this);
                        try {
                            mWallManager.suggestDesiredDimensions(ScreenUtil.getDisplayWidth(), ScreenUtil.getDisplayHeight());
                            mWallManager.setBitmap(resource);
                            if (mLoadDialog != null) {
                                mLoadDialog.dismiss();
                            }
                            ToastUtils.showToast("设置成功");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
                break;
        }
    }
}
